<?php
/**
 * Admin Service
 * User: zng
 * Date: 2019/11/4
 * Time: 14:34
 */
namespace app\admin\service\user;

use app\admin\model\user\UserNumber;

Class Info {

    /**
     * 首页列表
     * @author zx
     * @date 2019-11-08
     * @return \think\Paginator
     */
    public function indexPaginate( array $get=[] )
    {
        $map = [];
        if ( get($get, 'mobile') ) {
            $map[] = ['mobile', '=', $get['mobile']];
        }
        if ( get($get, 'number') ) {
            $map[] = ['number', '=', $get['number']];
        }
        $status = get($get, 'status');
        if ( $status === 0 || $status === '0' || $status == 1 ) {
            $map[] = ['status', '=', $status];
        }
        if ( get($get, 'start_create_at') ) {
            $map[] = ['create_at', '>=', $get['start_create_at'].' 00:00:00'];
        }
        if ( get($get, 'end_create_at') ) {
            $map[] = ['create_at', '<=', $get['end_create_at'].' 23:59:59'];
        }
        $pageSize = get($get,'pageSize')>0?$get['pageSize']:20;
        return UserNumber::with('userInfo')->where($map)->field('id,mobile,number,create_at,update_at,status')
            ->order('id', 'desc')
            ->paginate($pageSize);
    }

    /**
     * 更改状态
     * @author zx
     * @date 2019-12-17
     * @return \think\response
     */
    public function status(UserNumber $userNumber)
    {
        $status = (int)(!$userNumber->status);
        $userNumber->status = $status;
        $update = $userNumber->save();
        if ( $update ) {
            return success(['status'=>$status]);
        }
        return failed('更新失败');
    }

    /**
     * 更改管理员信息
     * @param int $id
     * @param array $data 数据包
     * @author zx
     * @date 2019-11-12
     * @return boolean
     */
    public function save(int $id, array $data)
    {
        return (new UserNumber())
            ->allowField(['mobile','number','status'])
            ->isUpdate()->save($data, ['id'=>$id]);
    }

    /**
     * 给管理员分配角色
     * @param int $id
     * @param array $rid 角色列表
     * @author zx
     * @date 2019-11-12
     * @throws Exception
     * @return boolean
     */
    public function role( int $id, array $rid )
    {
        app('rbac')->assignUserRole($id, $rid);
        return true;
    }

    /**
     * 判断是否唯一
     * @param array $data
     * @author zx
     * @date 2019-11-12
     * @return boolean
     */
    public function only(array $data)
    {
        $map = [];
        $id = get($data, 'id', 0);
        if ( get($data, 'mobile') ) {
            $map[] = ['mobile', '=', $data['mobile']];
        }
        if ( get($data, 'number') ) {
            $map[] = ['number', '=', $data['number']];
        }
        $idResult = UserNumber::where($map)->column('id');
        foreach ( $idResult as $_id ) {
            if ( $_id != $id ) {
                return false;
            }
        }
        return true;
    }


}